package com.snb.play.dwebtoon;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.Collator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONObject;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.snb.play.dwebtoon.data.DTO_Episode;
import com.snb.play.dwebtoon.data.DTO_EpisodeDatas;
import com.snb.play.dwebtoon.data.DTO_EpisodeImage;
import com.snb.play.dwebtoon.data.DTO_WebToon;
import com.snb.play.dwebtoon.data.EpData;
import com.snb.play.dwebtoon.util.BinderManager;
import com.snb.play.dwebtoon.util.DBProvider;
import com.snb.play.dwebtoon.util.FileManager;
import com.snb.play.dwebtoon.util.ImageDownloader;
import com.snb.play.dwebtoon.util.Logger;
import com.snb.play.dwebtoon.util.SharedData;

public class ContentListActivity extends BaseActivity implements OnMenuItemClickListener {

	public static String TAG = ContentListActivity.class.getSimpleName();
	private GridView mView;
	private boolean mEditMode = false;
	public static final String TOONNAME = "TOONNAME";
	public static int mSeleIdx;
	private SharedData mSharedData = null;
	Handler gBaseHandler = new Handler();
	// private DTO_EpisodeDatas mDatas = null;
	public ArrayList<DTO_Episode> mDatas;
	WebToonListAdapter mAdapter = null;

	Thread mStartGetData = new Thread(new Runnable() {

		@Override
		public void run() {

			try {
				JSONObject lEpObject = getRest().getDaumWebToonInfo(mSharedData.mMainNickName);

				if (mDatas != null && mDatas.size() == Integer.parseInt(lEpObject.getJSONObject("page").getString("totalItemCount"))) {
					mStartGetData.interrupt();
				} else {
					DBProvider.getInstance().begin();
					DTO_EpisodeDatas lDatas = new DTO_EpisodeDatas(lEpObject.getJSONObject("data"), mSharedData.mMainId);
					lDatas.id = mSharedData.mMainId;
					lDatas.insertObjToDB();
					Logger.d(TAG, "세팅");
					if (mDatas != null) {
						Logger.d(TAG, "mDatas != null && mDatas != null");
						for (DTO_Episode lEpisode : lDatas.webtoonEpisodes) {
							boolean isHasSame = false;
							for (DTO_Episode lM_Episode : mDatas) {
								if (lEpisode.id.equalsIgnoreCase(lM_Episode.id)) {
									isHasSame = true;
									break;
								}
							}
							if (!isHasSame && mAdapter != null) {
								// mAdapter.add(lEpisode);
								mDatas.add(lEpisode);
								lEpisode.insertObjToDB();
							}
						}
						// mDatas.insertObjToDB();
					} else {
						Logger.d(TAG, "mDatas = lDatas");
						mDatas = lDatas.webtoonEpisodes;
					}

					DBProvider.getInstance().close();
				}
			} catch (Exception e) {
				Logger.e(TAG, e.toString());
			} finally {
				mDatas = new ArrayList<DTO_Episode>();
				DTO_Episode lEpisode = new DTO_Episode();
				lEpisode.pid = mSharedData.mMainId;
				mDatas = DBProvider.getInstance().getAllObjByID(lEpisode);
				Collections.sort(mDatas, myComparator);
				Collections.reverse(mDatas);

				gBaseHandler.post(new Runnable() {

					@Override
					public void run() {
						// TODO Auto-generated method stub
						mAdapter = new WebToonListAdapter(getApplicationContext());
						mView.setAdapter(mAdapter);
						int position = 0;
						boolean isRead = false;
						for (DTO_Episode lEp : mDatas) {

							if (lEp.isReadFinish.equalsIgnoreCase("Y")) {
								mView.setSelection(position - 1);
								isRead = true;
								break;
							}
							position++;
						}

						if (!isRead)
							if (mDatas.size() >= position)
								mView.setSelection(position - 1);
						closeProgressDialog();
					}
				});
			}
		}
	}, TAG);

	private ImageDownloader downloader = new ImageDownloader();
	private boolean wasUpdate = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_list2);
		if (PACKEGNAME == null || PACKEGNAME.length() < 3)
			PACKEGNAME = getPackageName();
		mCheckeds = new HashMap<String, String>();
		downloader.clearCache();
	}

	@Override
	protected void onDestroy() {
		if (!mStartGetData.isInterrupted()) {
			mStartGetData.interrupt();
		}

		super.onDestroy();
	}

	@Override
	protected void onResume() {
		super.onResume();
		mView = (GridView) findViewById(R.id.main_list);
		mView.setNumColumns(3);

		if (!getIntent().getBooleanExtra("BACK", false)) {
			if (!getIntent().getBooleanExtra("GETNEXT", false)) {
				mSharedData = (SharedData) getIntent().getSerializableExtra(ContentListActivity.TOONNAME);
				mDatas = new ArrayList<DTO_Episode>();
				DTO_Episode lEpisode = new DTO_Episode();
				lEpisode.pid = mSharedData.mMainId;
				mDatas = DBProvider.getInstance().getAllObjByID(lEpisode);

				if (mDatas != null && mDatas.size() > 0) {
					Collections.sort(mDatas, myComparator);
					Collections.reverse(mDatas);
					mAdapter = new WebToonListAdapter(getApplicationContext());
					mView.setAdapter(mAdapter);
					int position = 0;
					boolean isRead = false;
					for (DTO_Episode lEp : mDatas) {

						if (lEp.isReadFinish.equalsIgnoreCase("Y")) {
							mView.setSelection(position);
							isRead = true;
							break;
						}
						position++;
					}

					if (!isRead)
						if (mDatas.size() > position)
							mView.setSelection(position);

				}
			}
		}
		try {
			if (!mStartGetData.isAlive()) {
				if (!mStartGetData.isInterrupted()) {
					mStartGetData.interrupt();
				}
				if (!wasUpdate) {
					showProgressDialog();
					mStartGetData.start();
					wasUpdate = true;
				}
			}
		} catch (Exception e) {

		}

		setLastToonUp(mSharedData.mMainId, false);
	}

	public void onItemDownLoad(int... aIdx) {
		mSharedData.mEpisodes.clear();
		for (int lInt : aIdx) {
			EpData lEpData = new EpData();
			lEpData.id = mDatas.get(lInt).id;
			lEpData.title = mDatas.get(lInt).title;
			lEpData.thumbUrl = mDatas.get(lInt).thumbnailImage;
			mSharedData.mEpisodes.add(lEpData);
		}
		gBinderManager.getService().setToonLoaderTask(mSharedData.mMainId, mSharedData);

	}

	public void onALLItemDownLoad() {
		for (DTO_Episode lEpisode : mDatas) {
			EpData lEpData = new EpData();
			lEpData.id = lEpisode.id;
			lEpData.title = lEpisode.title;
			lEpData.thumbUrl = lEpisode.thumbnailImage;
			mSharedData.mEpisodes.add(lEpData);
		}
		gBinderManager.getService().setToonLoaderTask(mSharedData.mMainNickName, mSharedData);

	}

	final int FULLTAG = 320480;
	private AlertDialog mDownLoadDialog;
	private Map<String, String> mCheckeds;

	private void downLoadDialog(final int... aIds) {
		if (mDatas.size() == 0)
			return;
		if (mDownLoadDialog == null || !mDownLoadDialog.isShowing()) {
			StringBuilder lMsg = new StringBuilder();
			lMsg.append(" '");
			lMsg.append(mSharedData.mToonName);
			lMsg.append("' 의\n");

			if (aIds.length == 1 && aIds[0] == FULLTAG) {
				if (mDatas.size() == 0)
					return;
				lMsg.append("'" + mDatas.get(mDatas.size() - 1).title + "' ~\n");
				lMsg.append("'" + mDatas.get(0).title + "'");
				lMsg.append("을 \n다운 로드 하시겠습니까?");
			} else {
				boolean isAppends = false;
				for (int lId : aIds) {
					if (isAppends)
						lMsg.append(", ");
					lMsg.append("'" + mDatas.get(lId).title + "'");
					isAppends = true;
				}
				lMsg.append(" 을 \n다운 로드 하시겠습니까?");
			}
			AlertDialog.Builder lDB = new AlertDialog.Builder(ContentListActivity.this);
			lDB.setMessage(lMsg.toString());

			lDB.setPositiveButton("다운로드", new AlertDialog.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					if (aIds[0] == FULLTAG) {
						onALLItemDownLoad();
					} else {
						onItemDownLoad(aIds);
					}
					mEditMode = false;
					mView.invalidateViews();
					mCheckeds.clear();
				}
			});
			lDB.setNegativeButton("다운로드 안함", new AlertDialog.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					mEditMode = false;
					mView.invalidateViews();
					mCheckeds.clear();
				}
			});

			mDownLoadDialog = lDB.create();
			mDownLoadDialog.show();
		}
	}

	@Override
	public boolean onMenuItemClick(MenuItem item) {
		switch (item.getItemId()) {
			case 0: {
				if (mCheckeds.size() > 0) {
					int[] lInts = new int[mCheckeds.size()];
					int idx = 0;
					for (String ll : mCheckeds.keySet()) {
						lInts[idx++] = Integer.parseInt(ll);
					}
					downLoadDialog(lInts);
				} else
					downLoadDialog(FULLTAG);
			}
				break;
			case 1: {
				showProgressDialog();
				deleteItem(mSharedData.mMainNickName.trim());
				closeProgressDialog();
				onBackPressed();
			}
				break;
		}

		return false;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_main3, menu);
		menu.add(0, 0, 0, "SAVE").setOnMenuItemClickListener(this);
		menu.add(1, 1, 1, "DELETE").setOnMenuItemClickListener(this);
		return true;
	}

	private class WebToonListAdapter extends ArrayAdapter<DTO_Episode> {

		public WebToonListAdapter(Context context) {
			super(context, R.layout.content_item, mDatas);
		}

		@Override
		public void add(DTO_Episode object) {
			super.add(object);
		}

		@Override
		public void notifyDataSetChanged() {
			super.notifyDataSetChanged();
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View row = convertView;
			ViewWrapper wrapper = null;

			if (row == null) {
				row = getLayoutInflater().inflate(R.layout.content_item, null);
				wrapper = new ViewWrapper(row);
				row.setTag(wrapper);
			} else {
				wrapper = (ViewWrapper) row.getTag();
			}

			final DTO_Episode info = getItem(position);

			final int idx = position;
			wrapper.mSaved.setText("");

			if (mEditMode) {
				wrapper.mCheckBox.setVisibility(View.VISIBLE);
				String kv = String.valueOf(idx);
				wrapper.mCheckBox.setChecked(mCheckeds.containsKey(kv));
				wrapper.mCheckBox.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						String kv = String.valueOf(idx);
						if (((CheckBox) v).isChecked()) {
							if (!mCheckeds.containsKey(kv)) {
								mCheckeds.put(kv, kv);
							}
						} else {
							if (mCheckeds.containsKey(kv)) {
								mCheckeds.remove(kv);
							}
						}
					}
				});
			} else {
				wrapper.mCheckBox.setVisibility(View.GONE);
			}

			downloader.download(info.thumbnailImage, wrapper.mThumb, makeFileName(info.thumbnailImage));

			wrapper.mSubTitle.setText(info.title);

			boolean isSaved = false;
			String lViewId = info.id;
			// DTO_EpisodeImage lImg = new DTO_EpisodeImage();
			// lImg.pid = info.id;
			if (isSavedItem(info.id)) {
				wrapper.mSaved.setText("저장되있음");
				wrapper.mSaved.setTextColor(0xFFFFFFFF);
				isSaved = true;
				if (getItem(position).isSavedInfo.indexOf("N") > -1) {
					getItem(position).isSavedInfo = "Y";
					DBProvider.getInstance().updateObjById(getItem(position));
				}
			} else {
				wrapper.mSaved.setTextColor(0xFFAAAAFF);
			}

			if (getItem(position).isReadFinish.indexOf("Y") > -1) {
				wrapper.mSaved.setText("다읽음");
			}

			final boolean fIsSaved = isSaved;
			final String fViewId = lViewId;

			if (!gBinderManager.getService().haveToonLoaderTsk(getItem(idx).id)) {
				wrapper.mBase.setAlpha(1.0f);
				if (!mEditMode)
					row.setOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View v) {
							Logger.d(TAG, fViewId);
							goToView(idx, fViewId, fIsSaved);
						}
					});
				if (!mEditMode) {
					row.setOnLongClickListener(new OnLongClickListener() {

						@Override
						public boolean onLongClick(View v) {
							if (!mEditMode) {
								mEditMode = true;
								mView.invalidateViews();
							}
							return true;
						}
					});
				} else {
					row.setOnLongClickListener(null);
				}
			} else {
				wrapper.mBase.setAlpha(0.5f);
				row.setOnLongClickListener(null);
				row.setOnClickListener(null);
			}

			return row;
		}

		private class ViewWrapper {
			private View mBase;
			private TextView mSaved;
			private TextView mSubTitle;
			private ImageView mThumb;
			private CheckBox mCheckBox;

			public ViewWrapper(View base) {
				mBase = base;

				if (mCheckBox == null) {
					mCheckBox = (CheckBox) mBase.findViewById(R.id.ch_down);
					// mmmthumb.setSelected(true);
				}
				if (mSaved == null) {
					mSaved = (TextView) mBase.findViewById(R.id.saved);
					// mmmthumb.setSelected(true);
				}

				if (mThumb == null) {
					mThumb = (ImageView) mBase.findViewById(R.id.thumb);
					// mmmthumb.setSelected(true);
				}

				if (mSubTitle == null) {
					mSubTitle = (TextView) mBase.findViewById(R.id.subtitle);
					mSubTitle.setSelected(true);
				}
			}

		}

	}

	private boolean isSavedItem(String aId) {
		DTO_EpisodeImage lImg = new DTO_EpisodeImage();
		lImg.pid = aId;
		return DBProvider.getInstance().getSelectObjTotalSize(lImg) > 0;
	}

	public void goToView(int idx, String aViewId, boolean aisSaved) {
		mSeleIdx = idx;
		setLastToonUp(mSharedData.mMainId, true);
		mSharedData.mToonId = aViewId;

		startActivityForResult(new Intent(ContentListActivity.this, ToonViewActivity.class).putExtra(ContentListActivity.TOONNAME, mSharedData)
				.putExtra(ToonViewActivity.WebDirectedUrl, aisSaved), FLAG_VIEW);
		overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
	}

	public static final int FLAG_VIEW = 830;
	public static final int FLAG_PREV = 829;
	public static final int FLAG_NEXT = 831;

	private final static Comparator<DTO_Episode> myComparator = new Comparator<DTO_Episode>() {

		private final Collator collator = Collator.getInstance();

		@Override
		public int compare(DTO_Episode object1, DTO_Episode object2) {
			int diff = object1.id.length() - object2.id.length();
			String objStr1 = object1.id;
			String objStr2 = object2.id;
			if (diff > 0)
				objStr2 = "0" + object2.id;
			else if (diff < 0)
				objStr1 = "0" + object1.id;

			return collator.compare(objStr1, objStr2);
		}
	};

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		Logger.d(TAG, "requestCode == " + requestCode + " resultCode == " + resultCode);
		if (mSharedData == null)
			mSharedData = (SharedData) getIntent().getSerializableExtra(ContentListActivity.TOONNAME);
		if (mDatas == null) {
			DTO_Episode lEpisode = new DTO_Episode();
			lEpisode.pid = mSharedData.mMainId;
			mDatas = DBProvider.getInstance().getAllObjByID(lEpisode);
			// mDatas = (DTO_EpisodeDatas)
			// FileManager.loadObj(getApplicationContext(),
			// FileManager.TOONSPATH + mSharedData.mMainNickName,
			// mSharedData.mMainNickName + ".lst");
			Collections.sort(mDatas, myComparator);
			Collections.reverse(mDatas);
		}

		if (resultCode == FLAG_PREV) {
			if (mSeleIdx < mDatas.size() - 1) {
				mSeleIdx++;
				goToView(mSeleIdx, mDatas.get(mSeleIdx).id, isSavedItem(mDatas.get(mSeleIdx).id));

			} else {
				onBackPressed();
			}
		} else if (resultCode == FLAG_NEXT) {
			if (mSeleIdx > 0) {
				mSeleIdx--;

				goToView(mSeleIdx, mDatas.get(mSeleIdx).id, isSavedItem(mDatas.get(mSeleIdx).id));

			} else {
				onBackPressed();
			}
		}

	}

	public static String PACKEGNAME;

	public static Bitmap getBitmapDrawable(String aUrl) {

		File lTempFile = null;
		String fileName = makeFileName(aUrl);
		String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Android/data/" + PACKEGNAME + "/temp";

		String extState = Environment.getExternalStorageState();

		if (extState.equals(Environment.MEDIA_MOUNTED)) {
			File lPath = new File(path);
			if (!lPath.exists())
				lPath.mkdirs();

			lTempFile = new File(path, fileName);
			if (lTempFile.exists())
				return BitmapFactory.decodeFile(lTempFile.getAbsolutePath());
		}

		return null;
	}

	public static String makeFileName(String aUrl) {
		String[] returnStrs = aUrl.split("/");
		return returnStrs[returnStrs.length - 1];
	}

	public static void saveFile(Bitmap bitmap, String fileName) {
		File lTempFile = null;
		Logger.d(TAG, "saveFile -> " + fileName);
		String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Android/data/" + PACKEGNAME + "/temp";

		String extState = Environment.getExternalStorageState();

		if (extState.equals(Environment.MEDIA_MOUNTED)) {
			File lPath = new File(path);
			if (!lPath.exists())
				lPath.mkdirs();

			lTempFile = new File(path, fileName);

			FileOutputStream out;
			if (bitmap != null) {
				try {
					out = new FileOutputStream(lTempFile);
					Logger.d(TAG, fileName + "  size == " + bitmap.getRowBytes());
					float scale = 180 / bitmap.getRowBytes();
					int quality = (int) (40 * scale);
					if (quality < 40)
						quality = 40;
					else if (quality > 60)
						quality = 60;

					bitmap.compress(Bitmap.CompressFormat.JPEG, quality, out);
					try {
						out.close();
					} catch (IOException e) {
						e.printStackTrace();
						bitmap.recycle();
					}
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				}
			}
		}

	}

	public String pinpToStr(InputStream inputStream) {

		StringBuffer out = new StringBuffer();
		try {

			byte[] buffer = new byte[4094];
			for (int n; (n = inputStream.read(buffer)) != -1;) {
				String lkj = new String(buffer, 0, n);
				Logger.d(TAG, lkj);
				out.append(lkj);

			}
		} catch (Exception e) {

		}

		return out.toString();
	}

	@Override
	public void onBackPressed() {
		if (mEditMode) {
			mEditMode = false;
			mView.invalidateViews();
		} else {
//			startActivity(new Intent(ContentListActivity.this, WebToonListActivity.class).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
			this.finish();
//			super.onBackPressed();
		}
	}

	public void showProgressDialog() {
		if (gProgressDialog == null) {
			gProgressDialog = new ProgressDialog(this);
			gProgressDialog.setTitle("처리중...");
			gProgressDialog.setIcon(R.drawable.snb_comic_icon);
			gProgressDialog.setCancelable(false);
			gProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);

		}

		if (!gProgressDialog.isShowing()) {
			gProgressDialog.show();
		}
	}

	public void closeProgressDialog() {
		if (gProgressDialog != null && gProgressDialog.isShowing()) {
			gProgressDialog.dismiss();
		}
	}

	public static void deleteReadedItem(String itemId) {

		String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Android/data/" + BinderManager.PKG_NAME + FileManager.TOONSPATH;

		String extState = Environment.getExternalStorageState();

		if (extState.equals(Environment.MEDIA_MOUNTED)) {
			File lFile = new File(path, itemId + ".tit");
			File lRead = new File(path, itemId + ".tid");
			if (lFile.exists())
				lFile.renameTo(lRead);

		}
	}

	public void deleteItem(String itemId) {

		String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Android/data/" + BinderManager.PKG_NAME + FileManager.TOONSPATH;
		DTO_EpisodeImage lEpisodeImage = new DTO_EpisodeImage();
		lEpisodeImage.main_id = mSharedData.mMainId;
		DBProvider.getInstance().deleteObjByID(lEpisodeImage);
		String extState = Environment.getExternalStorageState();

		if (extState.equals(Environment.MEDIA_MOUNTED)) {
			File lFile = new File(path, itemId);
			if (lFile.exists() && lFile.isDirectory()) {
				for (File lChildFile : lFile.listFiles()) {
					if (!lChildFile.getName().endsWith("lst")) {
						Logger.d(TAG, "deleteItem( " + itemId + " ) ->" + lChildFile.getName());
						if (lChildFile.isDirectory()) {
							for (File lCcFile : lChildFile.listFiles()) {
//								gBinderManager.getService().deleteFileSize(lCcFile.length());
								lCcFile.delete();
							}
							lChildFile.delete();
						} else {
							lChildFile.delete();
						}
					}
				}
			}
		}

		DTO_WebToon lDto_WebToon = new DTO_WebToon();
		lDto_WebToon.id = mSharedData.mMainId;
		lDto_WebToon.savedYn = "N";
		DBProvider.getInstance().updateObjById(lDto_WebToon);
	}


	@Override
	protected void refresh(String aString) {
		// TODO Auto-generated method stub
		Toast.makeText(this, aString + " 다운 완료!", Toast.LENGTH_LONG).show();
		if (mView != null)
			mView.invalidateViews();
	}


}
